//下载express  npm i express -S
const express = require('express');
const app = express();
const joi = require('@hapi/joi');
const cors = require('cors');
// 引入jwt包
const expressJWT = require('express-jwt');
const { secretKey } = require('./config');

const router = require('./router/user');
const userInfoRouter = require('./router/userinfo');
const artRouter = require('./router/artcate');
const articleRouter = require('./router/article');
const port = 3000;

// 配置跨域
app.use(cors());

app.use((req, res, next) => {
  res.cc = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});

app.use(expressJWT({ secret: secretKey }).unless({ path: [/^\/api\//] }));

// 解析表单数据 x-www-urlencoded
app.use(express.urlencoded({ extended: false }));

// 注册路由
app.use('/api', router);
app.use('/my', userInfoRouter);
app.use('/my/article', artRouter);
app.use('/my/article', articleRouter);

app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    res.cc('没有权限');
    return;
  }
  res.cc(err.message);
});
app.listen(port, () =>
  console.log(`Server running at  http://127.0.0.1:${port}`)
);

// 新建一个api_server文件夹
// npm init -y
// npm install express -S
// 在api_server下面创建app.js文件
// 创建express服务器

// npm i cors;

// npm i @escook/express-joi -S
